package utils

import (
	"context"
	"log"
	"sync"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	mongoClient *mongo.Client
	mongoOnce   sync.Once
)

// InitMongo 初始化 MongoDB 客户端（只执行一次）
func InitMongo(dbAddr string) error {
	var err error
	mongoOnce.Do(func() {
		clientOptions := options.Client().ApplyURI(dbAddr)
		mongoClient, err = mongo.Connect(context.TODO(), clientOptions)
		if err != nil {
			log.Println("connect mongo fail:", err)
			return
		}
		err = mongoClient.Ping(context.TODO(), nil)
		if err != nil {
			log.Println("mongo ping fail:", err)
		} else {
			log.Println("MongoDB connect success")
		}
	})
	return err
}

// GetMongoClient 获取 MongoDB 客户端
func GetMongoClient() *mongo.Client {
	return mongoClient
}
